//
//  BHCMPedimeter.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/8/27.
//

import UIKit
import CoreMotion

class BHCMPedimeter: NSObject {
    
    var stepPedometerHandler: ((Double) -> Void)?
    
    
    lazy var pedometer = CMPedometer.init()
    
    func startPedometer() {
        if CMPedometer.isDistanceAvailable() {
            self.pedometer.startUpdates(from: Date()) { (pedometerDate, error) in
                guard error == nil else {
                    self.stepPedometerHandler?(0.0)
                    BHCommonTool.showAlertWith(showVC: nil, title: "提示", message: "您暂未打开计步器授权，请至 设置->隐私->运动与健康 打开权限", okBtn: "知道了", cancel: nil) { (_) in
                        
                    }
                    return
                }
                if let distance = pedometerDate?.distance {
                    print("获取到距离: \(distance)")
                    self.stepPedometerHandler?(distance.doubleValue)
                }
                
            }
        }else {
            self.stepPedometerHandler?(0.0)
        }
    }
    
    func stopPedometer()  {
        self.pedometer.stopUpdates()
    }
}
